package com.globallogic.anagrams;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * Determines whether the entered strings are the anagrams.
 */
public class Anagrams {
    public static void main(String[] args) {
            if (isAnagrams(inputString("Input first string: "),
                           inputString("Input second string: "))) {
                System.out.print("These strings are anagrams.");
            } else {
                System.out.print("These strings aren't anagrams.");
            }
    }

    private static String inputString(String description) {
        String SPACE = " ";
        String EMPTY = "";
        String inputStr = EMPTY;
        try {
            BufferedReader bReader = new BufferedReader(new InputStreamReader(System.in));
            System.out.print(description);
            inputStr = bReader.readLine();
            inputStr = inputStr.replaceAll(SPACE, EMPTY);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return inputStr;
    }

    /**
     * @param firstString - First entered string without spaces.
     * @param secondString - Second entered string without spaces.
     * @return  If these strings are anagram then return true else false.
     */
    private static boolean isAnagrams(String firstString, String secondString) {
        char CH_EMPTY = Character.UNASSIGNED;
        boolean result = true;
        int i = 0;

        if (firstString.length() == secondString.length()) {
            int charCount = firstString.length();
            char chars[] = new char[charCount];

            firstString.getChars(0, charCount, chars, 0);

            do {
                if (secondString.indexOf(chars[i]) >= 0) {
                    secondString = secondString.replace(chars[i], CH_EMPTY);
                    secondString = secondString.trim();
                    i++;
                } else {
                    result = false;
                }
            }
            while (result && (i < charCount));

            if (secondString.length() > 0) {
                result = false;
            }
        } else {
            result = false;
        }
        return result;
    }
}